package com.kkd.kkdapp.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;

import com.kkd.kkdapp.R;
import com.kkd.kkdapp.activity.HomeActivity;

public class UpdateApkManager {

	private Context mContext;
	private Dialog mDialog;
	// 提示语
	private String updateMsg = "有最新的软件包哦，亲快下载吧~";
	// 返回的安装包url
	private String apkUrl;
	private int mustUpdateStatus;
	private static String versionId;

	private Dialog sureDialog;

	private Dialog downloadDialog;
	/* 下载包安装路径 */
	private static final String savePath = FileUtils.getKKDRootPath() + "apk/";
	private static final String savePathTemp = FileUtils.getKKDRootPath()
			+ "temp/";

	// private static final String saveFileName = savePath + "kuaikuaidai.apk";

	private static String saveFileName = savePath + "kuaikuaidai_" + versionId
			+ ".apk";
	private static String saveFileTemp = savePathTemp + "kuaikuaidai_"
			+ versionId + ".apk";

	/* 进度条与通知ui刷新的handler和msg常量 */
	private ProgressBar mProgress;

	private static final int DOWN_UPDATE = 1;

	private static final int DOWN_OVER = 2;

	private int progress;

	private Thread downLoadThread;

	private boolean interceptFlag = false;

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DOWN_UPDATE:
				if (mProgress != null)
					mProgress.setProgress(progress);
				break;
			case DOWN_OVER:
				if (downloadDialog != null) {
					downloadDialog.dismiss();
				}
				showExistsDialog(mustUpdateStatus);
				// installApk();
				break;
			default:
				break;
			}
		};
	};

	public UpdateApkManager(Context context) {
		this.mContext = context;
		File file = new File(savePath);
		if (!file.exists()) {
			file.mkdir();
		}
	}

	// 外部接口让主Activity调用
	public void checkUpdateInfo(String appVersion, String imgUrl,
			String versionDesc, String url, String versionId,
			int mustUpdateStatus) {
		this.apkUrl = url;
		this.versionId = versionId;
		this.mustUpdateStatus = mustUpdateStatus;
		saveFileName = savePath + "kuaikuaidai_" + versionId + ".apk";
		saveFileTemp = savePathTemp + "kuaikuaidai_" + versionId + ".apk";
		if (FileUtils.isFileUrlExit(FileUtils.getKKDRootPath() + "apk/"
				+ "kuaikuaidai_" + versionId + ".apk")) {
			// 文件已存在是否安装
			if (downloadDialog == null || !downloadDialog.isShowing()) {
				showExistsDialog(mustUpdateStatus);
			}
		} else {
			if (downloadDialog == null || !downloadDialog.isShowing()) {
				showNoticeDialog(mustUpdateStatus, imgUrl, versionDesc,
						appVersion);
			}
		}
	}

	private void showNoticeDialog(final int mustUpdateStatus, String imgUrl,
			String versionDesc, String appVersion) {
		if (mDialog != null) {
			mDialog.cancel();
			mDialog = null;
		}
		// mDialog = DialogUtils.updateEdition(mContext, imgUrl, versionDesc,
		// mustUpdateStatus, appVersion,
		// new android.view.View.OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// switch (v.getId()) {
		// case R.id.confirm_deletebank:
		// mDialog.dismiss();
		// SystemUtils.onEvent("UpdatePop_unpdate", 1);
		// showDownloadDialog(mustUpdateStatus);
		// break;
		// case R.id.cancel_deletebank:
		// if (mustUpdateStatus == 0) {
		// mDialog.dismiss();
		// } else if (mustUpdateStatus == 1) {
		// // mDialog.dismiss();
		// // ((Activity) mContext).finish();
		// // System.exit(0);
		// }
		// break;
		// }
		// }
		// });
		mDialog = DialogUtils.updateDialog(mContext, versionDesc,
				mustUpdateStatus, appVersion,
				new android.view.View.OnClickListener() {

					@Override
					public void onClick(View v) {
						switch (v.getId()) {
						case R.id.bottom_toUpdate:
							if (mDialog != null) {
								mDialog.dismiss();
							}
							SystemUtils.onEvent("UpdatePop_unpdate", 1);
							showDownloadDialog(mustUpdateStatus);
							break;

						case R.id.close:
							if (mDialog != null) {
								mDialog.dismiss();
							}
							if (mustUpdateStatus == 0) {
								((HomeActivity) mContext).checkRedpackage();
							} else if (mustUpdateStatus == 1) {
								((Activity) mContext).finish();
								System.exit(0);
							}
							break;

						default:
							break;
						}
					}
				});
		mDialog.show();
	}

	private void showDownloadDialog(final int mustUpdateStatus) {
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setTitle("快快贷理财版本更新");

		final LayoutInflater inflater = LayoutInflater.from(mContext);
		View v = inflater.inflate(R.layout.progress, null);
		mProgress = (ProgressBar) v.findViewById(R.id.progress);

		builder.setView(v);
		builder.setNegativeButton("取消", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// interceptFlag = true;
				String apkFile = saveFileTemp;
				File ApkFile = new File(apkFile);
				if (ApkFile.exists()) {
					ApkFile.delete();
				}

				dialog.dismiss();
				if (mustUpdateStatus == 1) {
					((Activity) mContext).finish();
					System.exit(0);
				}
			}
		});
		downloadDialog = builder.create();
		downloadDialog.setCancelable(false);
		downloadDialog.setCanceledOnTouchOutside(false);
		downloadDialog.show();

		downloadApk();

	}

	private Runnable mdownApkRunnable = new Runnable() {
		@Override
		public void run() {
			try {
				URL url = new URL(apkUrl);

				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.connect();
				int length = conn.getContentLength();
				InputStream is = conn.getInputStream();

				File file = new File(savePathTemp);
				if (!file.exists()) {
					file.mkdir();
				}
				String apkFile = saveFileTemp;
				File ApkFile = new File(apkFile);
				if (ApkFile.exists()) {
					ApkFile.delete();
				}
				FileOutputStream fos = new FileOutputStream(ApkFile);

				int count = 0;
				byte buf[] = new byte[1024];

				do {
					int numread = is.read(buf);
					count += numread;
					progress = (int) (((float) count / length) * 100);
					// 更新进度
					mHandler.sendEmptyMessage(DOWN_UPDATE);
					if (numread <= 0) {
						// 下载完成通知安装
						mHandler.sendEmptyMessage(DOWN_OVER);
						FileUtils.copyFile(saveFileTemp, saveFileName);
						break;
					}
					fos.write(buf, 0, numread);
				} while (!interceptFlag);// 点击取消就停止下载.

				fos.close();
				is.close();

			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	};

	/**
	 * 下载apk
	 * 
	 * @param url
	 */

	private void downloadApk() {
		downLoadThread = new Thread(mdownApkRunnable);
		downLoadThread.start();
	}

	/**
	 * 安装apk
	 * 
	 * @param url
	 */
	private void installApk() {
		File apkfile = new File(saveFileName);
		if (!apkfile.exists()) {
			return;
		}
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
				"application/vnd.android.package-archive");
		mContext.startActivity(i);

	}

	public void cancle() {
		if (mProgress != null)
			mProgress = null;
		if (downloadDialog != null) {
			downloadDialog.cancel();
			downloadDialog = null;
		}
		if (mDialog != null) {
			mDialog.cancel();
			mDialog = null;
		}
		if (sureDialog != null) {
			sureDialog.cancel();
			sureDialog = null;
		}
	}

	private void showExistsDialog(final int mustUpdateStatus) {
		if (sureDialog != null) {
			sureDialog.cancel();
			sureDialog = null;
		}
		sureDialog = DialogUtils.haveDownloadedDialog(mContext,
				"安装包已下载完毕，是否立即安装", new android.view.View.OnClickListener() {

					@Override
					public void onClick(View v) {
						switch (v.getId()) {
						case R.id.confirm_deletebank:
							if (sureDialog != null) {
								sureDialog.dismiss();
							}
							installApk();
							if (mustUpdateStatus == 1) {
								((Activity) mContext).finish();
								System.exit(0);
							}
							break;

						case R.id.redownload:
							if (sureDialog != null) {
								sureDialog.dismiss();
							}
							String apkFile = saveFileName;
							File ApkFile = new File(apkFile);
							if (ApkFile.exists()) {
								ApkFile.delete();
								showDownloadDialog(mustUpdateStatus);
							}
							break;

						case R.id.cancel_deletebank:
							if (sureDialog != null) {
								sureDialog.dismiss();
							}
							if (mustUpdateStatus == 1) {
								((Activity) mContext).finish();
								System.exit(0);
							}
							break;
						}
					}
				});
		sureDialog.show();
	}
}
